"use client"
import styles from './page.module.scss'
import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Modal, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { login, updUser } from '@/api/usersApi'

const getBase64 = (img: any, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const App = (prpos: any) => {
  const { isModalOpen, setIsModalOpen, userInfo, setUserInfo, imageUrlOld, setImageUrlOld } = prpos
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState(imageUrlOld);
  const [file, setFile] = useState('' as any);
  // 上传请求
  const handleUpload = () => {
    const formData = new FormData();
    formData.append('file', file);
    fetch(`http://120.55.191.224:8080/api/upload?id=${userInfo._id}`, {
      method: 'POST',
      body: formData,
    })
  };
  useEffect(() => {
    form.setFieldsValue(userInfo)
  }, [isModalOpen])
  const handleOk = async () => {
    const values = form.getFieldsValue();
    handleUpload()
    if (imageUrl) {
      values.picture = `http://120.55.191.224:8080/static/${userInfo._id}.png?time=${new Date().getTime()}`
    }
    setImageUrlOld(values.picture)
    await updUser({ ...userInfo, ...values })
    const res = await login({ _id: userInfo._id })
    setUserInfo(res.data)
    localStorage.setItem('userInfo', JSON.stringify({ ...userInfo, ...res.data }))
    message.success('操作成功');
    setIsModalOpen(false);
  };
  return (
    <>
      <Modal title='编辑个人信息' open={isModalOpen} onOk={handleOk} okText='确认' cancelText='取消' onCancel={() => setIsModalOpen(false)} forceRender>
        <Form form={form} layout='horizontal' wrapperCol={{ span: 16 }} labelCol={{ span: 4 }}>
          <Upload
            className={styles['avatar-uploader']}
            listType="picture-card"
            showUploadList={false}
            fileList={[file]}
            beforeUpload={(file: any) => {
              setFile(file);
              return false;
            }}
            onChange={(info) => {
              if (info.file.uid) {
                getBase64(info.file, (url: any) => {
                  setImageUrl(url);
                })
              }
            }}
            onRemove={() => {
              setImageUrl('');
              setFile('');
            }}
          >
            {imageUrl ?
              <img src={imageUrl} style={{ width: '100%', height: '100%', borderRadius: '8px' }} alt="avatar" /> :
              <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </button>}
          </Upload>
          <Form.Item label="客户类型" name="phone">
            <Input disabled />
          </Form.Item>
          <Form.Item label="用户名" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password">
            <Input />
          </Form.Item>
          <Form.Item label="手机号" name="phone">
            <Input />
          </Form.Item>
          <Form.Item label="身份证号" name="idCard">
            <Input disabled />
          </Form.Item>
          <Form.Item label="租赁天数" name="lastRentDays" >
            <InputNumber size='small' suffix="天" disabled />
          </Form.Item>
          <Form.Item label="信用评分" name="creditScore">
            <InputNumber size='small' suffix="分" disabled />
          </Form.Item>
          {userInfo?.customerType === '企业' && <Form.Item label="企业名称" name="companyName">
            <Input />
          </Form.Item>}
          <Form.Item label="地址" name="address">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default App;